<?php
declare (strict_types = 1);

namespace app\command;

use GuzzleHttp\Client;
use think\console\Command;
use think\console\Input;
use think\console\input\Argument;
use think\console\input\Option;
use think\console\Output;
use think\facade\Db;

class Extension extends Command
{
    protected function configure()
    {
        // 指令配置
        $this->setName('sync-extendsion')
            ->setDescription('the sync-extendsion command');
    }

    protected function execute(Input $input, Output $output)
    {
        //获取近30天推广数据
        $this->getExtension();

        // 指令输出
        $output->writeln('sync-extendsion');
    }

    protected function getExtension(){
        $url = 'https://buyin.jinritemai.com/pc/decision/promotion/data';
        $headers = [
            'user-agent' => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.114 Safari/537.36',
            'Referer' => 'https://buyin.jinritemai.com',
            'Cookie'=>config('app.buyin_author.cookie')
        ];
        //获取所有商品
        $goods = Db::name('activity_goods')->field('id,product_promotion_id')->select();

        if($goods){
            $goods = $goods->toArray();
            $client = new Client();
            foreach($goods as $k=>$v){
                $param = [
                    'promotion_id'=> $v['product_promotion_id']
                ];
                try {
                    $response = $client->request('GET', $url, ['query'=>$param, 'headers'=>$headers]);

                    $result = json_decode($response->getBody()->getContents(), true);

                    if($result['code'] == 0){
                        $data = $result['data'] ? json_encode($result['data']) : '';
                    }else{
                        $data = '';
                    }
                    Db::name('activity_goods')->where(['id'=>$v['id']])->update(['extension'=>$data]);
                } catch (\Exception $e) {
                    echo $e->getRequest();
                    if ($e->hasResponse()) {
                        echo $e->getResponse();
                    }
                }
                echo '.';
                if($k % 100 == 0) sleep(5);
            }
        }

    }
}
